﻿using System;
using System.Threading;
using System.Windows.Forms;
using CalcSharp.Core.NumberCache;

namespace CacheMaker
{
    public partial class Main : Form
    {
        Thread t;
        CacheData d;
        DateTime t1, t2;
        TimeSpan diff;
        bool v;

        public Main(bool verbose)
        {
            InitializeComponent();
            this.v = verbose;
            d = new CacheData();
            t = new Thread(this.ThredRun);
            t1 = DateTime.Now;
            t.Start();
        }

        delegate void SimpleCall();

        private void Ready()
        {
            t2 = DateTime.Now;
            diff = t2 - t1;
            if (v) MessageBox.Show("Cache Generation finished.\n\rElapsed time: " + diff.ToString(), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.t.Abort();
            this.t = null;
            this.Close();
        }

        private void ThredRun()
        {
            d.Initialize();
            this.Invoke(new SimpleCall(this.Ready));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (t != null)
            {
                if (t.IsAlive)
                {
                    t.Abort();
                    t = null;
                    d = null;
                    MessageBox.Show("Cache Generation failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
